package two_pointer;

/**
 * Created with IntelliJ IDEA.
 * Description: 151. 反转字符串中的单词
 * User: Li_yizYa
 * Date: 2025/5/12
 * Time: 21:54
 */
public class Solution4 {
    public static void main(String[] args) {
        System.out.println(reverseWords("          you   love   I "));
    }
    public static String reverseWords(String s) {
        if (s == null || s.length() == 0) {
            return null;
        }
        // 去除空格
        StringBuilder str = removeSpace(s);
        // 反转整个句子
        reverse(str, 0, str.length() - 1);
        // 反转每个单词
        int index = 0;
        for (int i = 0 ; i < str.length(); i++) {
            if (str.charAt(i) == ' ') {
                reverse(str, index, i - 1);
                index = i + 1;
            }
        }
        reverse(str, index, str.length() - 1);
        return str.toString();
    }

    private static StringBuilder removeSpace(String s) {
        StringBuilder ret = new StringBuilder();
        int left = 0;
        int right = s.length() - 1;
        // 去除左边界空格
        while (s.charAt(left) == ' ') {
            left++;
        }
        // 去除右边界空格
        while (s.charAt(right) == ' ') {
            right--;
        }
        for (int i = left; i <= right; i++) {
            if (s.charAt(i) != ' ' || s.charAt(i + 1) != ' ') {
                ret.append(s.charAt(i));
            }
        }
        return ret;
    }

    private static void reverse(StringBuilder s, int left, int right) {
        if (s == null || s.length() == 0 || left >= right) {
            return;
        }
        while (left < right) {
            char c = s.charAt(left);
            s.setCharAt(left, s.charAt(right));
            s.setCharAt(right, c);
            left++;
            right--;
        }
    }
}
